package 栈算法;

import org.junit.Test;

import java.util.Stack;

public class isPalindrome234 {
    /**
     * 判断是否为回文链表 如果是利用的栈的遍历的话o(n)
     *
     * @param head
     * @return
     */
    public boolean isPalindrome(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        if (head == null) {
            return true;
        }
        while (head != null) {
            if (stack.isEmpty()) {
                stack.add(head);
            } else {
                if (stack.peek() == head) {
                    stack.pop();
                } else {
                    stack.add(head);
                }
            }
            head = head.next;
        }
        return stack.size() == 0;
    }

    @Test
    public void test() {
        ListNode s0 = new ListNode(1);
        ListNode s1 = new ListNode(2);
        ListNode s2 = new ListNode(2);
        ListNode s3 = new ListNode(1);

        s0.next = s1;
        s1.next = s2;
        s2.next = s3;
        boolean palindrome = isPalindrome(s0);
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
